package cn.tx.config;

import cn.tx.service.impl.annotation.Log;
import cn.tx.service.impl.annotation.SysOperLog;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author: 可乐加糖
 * @create: 2023-03-20 14:30
 * @Description:
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    // 配置织入点
    @Pointcut("@annotation(cn.tx.service.impl.annotation.Log)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e) {
        try {
            // 获得注解
//            Log controllerLog = getAnnotationLog(joinPoint);
//            if (controllerLog == null) {
//                return;
//            }
//            // 获取当前的用户
//            SysUser currentUser = ShiroUtils.getSysUser();
//
//            // *========数据库日志=========*//
//            SysOperLog operLog = new SysOperLog();
//            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
//            // 请求的地址
//            String ip = ShiroUtils.getIp();
//            operLog.setOperIp(ip);
//
//            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
//            if (currentUser != null) {
//                operLog.setOperName(currentUser.getLoginName());
//                if (StringUtils.isNotEmpty(currentUser.getDept())
//                        && StringUtils.isNotEmpty(currentUser.getDept().getDeptName())) {
//                    operLog.setDeptName(currentUser.getDept().getDeptName());
//                }
//            }
//
//            if (e != null) {
//                operLog.setStatus(BusinessStatus.FAIL.ordinal());
//                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
//            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            //operLog.setMethod(className + "." + methodName + "()");
            // 保存数据库
            //AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }
}